extends StateBase

var battleField:BattleField
var attackTargetCells
var state = 0	# 0.select target 1.attacking 2.finish
var animationName
var targetEnemy
var enemyTargetFace

func enter():
	battleField = get_tree().get_nodes_in_group("BattleField")[0]
	
	attackTargetCells = [ownerNode.data.battlePos + Vector2(1, 0), ownerNode.data.battlePos + Vector2(-1, 0), ownerNode.data.battlePos + Vector2(0, 1), ownerNode.data.battlePos + Vector2(0, -1)]
	battleField.clearTargetHighlight()
	battleField.drawTargetHighlight(attackTargetCells)
	
	state = 0
	

func exit():
	pass


func run(delta):
	battleField.processCamMove(delta)
	battleField.processSelectCell(delta)
	
	processSelectAttackTarget(delta)
	processCancelAttack(delta)
	processAttackTarget(delta)
	
	
func processSelectAttackTarget(delta):
	if state != 0: return
	
	if Input.is_action_just_pressed("mouse_left_button"):
		var mousePositionCell = battleField.getMousePositionCell()
		var found = false
		var foundTargetCell = null
		for targetCell in attackTargetCells:
			if targetCell.x == mousePositionCell.x and targetCell.y == mousePositionCell.y:
				found = true
				foundTargetCell = targetCell
		if not found: return
		
		var enemy = battleField.findEnemyByCellPos(foundTargetCell)
		if enemy == null: return
		
		targetEnemy = enemy
		var face = battleField.dirVec2Face(foundTargetCell - ownerNode.data.battlePos)
		enemyTargetFace = battleField.dirVec2Face(ownerNode.data.battlePos - foundTargetCell)
		animationName = "Attack" + face
		ownerNode.data.battleFace = face
		ownerNode.animations.play(animationName)
		
		battleField.clearTargetHighlight()
		
		state = 1
	

func processAttackTarget(delta):
	if state != 1: return
	
	if ownerNode.animations.frame >= Consts.attackAnimationHitFrame[animationName]:
		state = 2
		
		targetEnemy.data.battleFace = enemyTargetFace
		targetEnemy.onHit()
		finishAttack()
		

func finishAttack():
	ownerNode.stateMachine.clearAndAddState(Consts.battleEntityStateIdle)
	battleField.finishExecuteCommand()
		
		
func processCancelAttack(delta):
	if state != 0: return
	
	if Input.is_action_just_pressed("mouse_right_button"):
		battleField.clearTargetHighlight()
		ownerNode.cancelExecuteCommand()
	
	
	
	
